package com.richfit.barcodesystem_cczt.activitis;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.richfit.barcodesystem_cczt.R;
import com.richfit.barcodesystem_cczt.activitis.adapters.BottomDialogMenuAdapter;
import com.richfit.barcodesystem_cczt.activitis.adapters.BottomSheetDialogAdapter;
import com.richfit.barcodesystem_cczt.activitis.adapters.MainAdapter;
import com.richfit.barcodesystem_cczt.activitis.base.BaseActivity;
import com.richfit.barcodesystem_cczt.activitis.model.UpdateInfo;
import com.richfit.barcodesystem_cczt.activitis.model.base.Result;
import com.richfit.barcodesystem_cczt.activitis.model.login.BottomMenuEntity;
import com.richfit.barcodesystem_cczt.activitis.model.users.UserInfo;
import com.richfit.barcodesystem_cczt.animation.DividerGridItemDecoration;
import com.richfit.barcodesystem_cczt.appcliation.MyAppcliation;
import com.richfit.barcodesystem_cczt.databinding.ActivityHomeBinding;
import com.richfit.barcodesystem_cczt.databinding.DialogBottomMenuBinding;
import com.richfit.barcodesystem_cczt.network.OkHttpUtils;
import com.richfit.barcodesystem_cczt.network.download.DownloadProgressListener;
import com.richfit.barcodesystem_cczt.network.download.DownloadUtil;
import com.richfit.barcodesystem_cczt.utils.Update;
import com.richfit.barcodesystem_cczt.utils.Urls;
import com.richfit.barcodesystem_cczt.utils.constant.Global;
import com.richfit.barcodesystem_cczt.utils.dialog.DialogHelper;
import com.richfit.barcodesystem_cczt.utils.sharedPreferences.DatabaseHelper;
import com.richfit.barcodesystem_cczt.utils.toast.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cl
 */
public class Home extends BaseActivity {

    private ActivityHomeBinding binding;
    private Dialog mBottomSheetDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        initData();
    }

    private void initView() {
        getUserInfo();
    }

    /**
     * 初始化数据；数据获取
     */
    private void initData() {
        binding.icdTop.IVBack.setOnClickListener(v -> exit());
        binding.icdTop.TxtTitle.setText(R.string.app_name);
        binding.fab.setOnClickListener(v -> showChooseDialog());
    }

    /**
     * 获取用户信息和菜单信息
     */
    void getUserInfo() {
        DialogHelper dialogHelper = new DialogHelper(this);
        dialogHelper.showLoadingDialog("正在获取用户信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_CURUSER, bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                UserInfo userInfo = gson.fromJson(data, UserInfo.class);
                //判断移动端菜单列表
                for (UserInfo.MenusBean menusBean : userInfo.getMenus()) {
                    if ("mobile".equals(menusBean.getPath())) {
                        userInfo.setMenus(menusBean.getChildren());
                        break;
                    }
                }
                DatabaseHelper.editSp(bo.userinfo, gson.toJson(userInfo));

                //获取仓库存储数据
                getStoreInfo();

                setMenuInfo();
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    /**
     * 设置页面菜单项
     *
     * @param
     */
    private void setMenuInfo() {

        UserInfo userInfo = gson.fromJson(DatabaseHelper.getSp(bo.userinfo, ""), UserInfo.class);
        if (userInfo == null) {
            return;
        }
        //九宫格
        List<UserInfo.MenusBean> list = userInfo.getMenus();
        if (list == null || list.size() <= 0) {
            return;
        }
        MainAdapter mainAdapter = new MainAdapter(this, list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3, RecyclerView.VERTICAL, false);
        binding.modularList.setLayoutManager(gridLayoutManager);
        binding.modularList.addItemDecoration(new DividerGridItemDecoration(this));
        binding.modularList.setAdapter(mainAdapter);
        // 设置数据后就要给RecyclerView设置点击事件,menusBean:九宫格单项的对象
        mainAdapter.setOnItemClickListener((position, menusBean) -> setOnItemClick(menusBean));
    }

    /**
     * 菜单点击事件
     *
     * @param menusBean
     */
    private void setOnItemClick(UserInfo.MenusBean menusBean) {
        //菜单的一级子菜单；比如：物资入口-（整箱入库，单项入库，批量入库）
        final List<UserInfo.MenusBean> bizMenuNodes = menusBean.getChildren();
        if (bizMenuNodes != null && bizMenuNodes.size() == 1) {
            toMain(Global.COMPANY_CODE, menusBean.getPath(),
                    bizMenuNodes.get(0).getPath(), "", bizMenuNodes.get(0).getName());

//            //如果第二级菜单自有一个（第二级菜单必须的个数必须大于等于1）
//            if (refMenuNodes != null && refMenuNodes.size() == 1) {
//                //如果单据也只有一个，那么直接进入业务MainActivity
//                toMain(Global.COMPANY_CODE, menusBean.getPath(),
//                        bizMenuNodes.get(0).getBusinessType(),
//                        refMenuNodes.get(0).getRefType(), bizMenuNodes.get(0).getCaption());
//            } else if (refMenuNodes == null || refMenuNodes.size() == 0) {
//                //如果没有第三级菜单，那么直接跳转
//                toMain(Global.COMPANY_CODE, menusBean.getPath(),
//                        bizMenuNodes.get(0).getBusinessType(),
//                        "", bizMenuNodes.get(0).getCaption());
//            } else {
//                //如果有多个单据，那么直接操作第三级
//                setupRefTypeDialog(bizMenuNodes.get(0), menusBean.getPath());
//            }
        } else if (bizMenuNodes == null || bizMenuNodes.size() == 0) {
            //没有第二级菜单.第三级菜单
            toMain(Global.COMPANY_CODE, menusBean.getPath(),
                    menusBean.getPath(),
                    "", menusBean.getName());

        } else {
            //如果子菜单有多个，那么用户需要先操作子菜单
            setupBizTypeDialog(menusBean);
        }
    }

    /**
     * 创建底部自子菜单功能列表对话框（PopUpWindow）
     *
     * @param menusBean:第一级节点菜单
     */
    public void setupBizTypeDialog(final UserInfo.MenusBean menusBean) {
        DialogBottomMenuBinding binding = DialogBottomMenuBinding.inflate(getLayoutInflater());
        BottomSheetDialogAdapter adapter = new BottomSheetDialogAdapter(this, menusBean.getChildren());
        binding.gdMenus.setAdapter(adapter);

        if (mBottomSheetDialog == null) {
            mBottomSheetDialog = new Dialog(this, R.style.MaterialDialogSheet);
        }

        mBottomSheetDialog.setContentView(binding.getRoot());
        mBottomSheetDialog.setCancelable(true);
        mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
        mBottomSheetDialog.show();

        //子菜单的点击事件监听
        binding.gdMenus.setOnItemClickListener((parent, view1, position, id) -> {
            //第二级菜单节点
            toMain(Global.COMPANY_CODE, menusBean.getPath(), menusBean.getChildren().get(position).getPath(),
                    "", menusBean.getChildren().get(position).getName());
//            final UserInfo.MenusBean item = adapter.getItem(position);
//            final List<> refMenuNodes = map.get(item.getId());
//            if (refMenuNodes != null && refMenuNodes.size() == 1) {
//                //如果第三级只有一个节点，那么直接进入业务界面
//                toMain(Global.COMPANY_CODE, moduleCode, item.getBusinessType(),
//                        refMenuNodes.get(0).getRefType(), item.getCaption());
//            } else if (refMenuNodes == null || refMenuNodes.size() == 0) {
//                toMain(Global.COMPANY_CODE, moduleCode, item.getBusinessType(),
//                        item.getRefType(), item.getCaption());
//            } else {
//                setupRefTypeDialog(item, moduleCode);
//            }
            mBottomSheetDialog.dismiss();
        });
    }

//    /**
//     * 用户选择单据类型
//     *
//     * @param menuNode：第二级节点
//     * @param moduleCode：第一级节点编码
//     */
//    private void setupRefTypeDialog(final MenuNode menuNode, final String moduleCode) {
//        final List<MenuNode> children = map.get(menuNode.getId());
//        if (children != null && children.size() > 0) {
//            final String[] items = new String[children.size()];
//            for (int i = 0; i < children.size(); i++) {
//                items[i] = children.get(i).getCaption();
//            }
//
//            new AlertView("请选择您需要操作的单据类型", null, "取消", null, items, this,
//                    AlertView.Style.ActionSheet, (o, position) -> {
//                Log.d("yff", "position = " + position);
//                if (position < 0)
//                    return;
//                toMain(Global.COMPANY_CODE, moduleCode, menuNode.getBusinessType(),
//                        children.get(position).getRefType(), children.get(position).getCaption());
//            }).show();
//        }
//    }

    /**
     * 调整到mainActivity,用户进行业务操作
     *
     * @param companyCode:公司编码
     * @param moduleCode:主模块编码
     * @param bizType:业务类型
     * @param refType:单据类型
     * @param caption:模块名称
     */
    private void toMain(String companyCode, String moduleCode, String bizType, String refType, String caption) {
        Log.i("yff", "HomeActivity.toMain: ".concat(bizType).concat(":").concat(refType));
        if (TextUtils.isEmpty(companyCode)) {
            ToastUtil.showTextShort("未获取到需要操作的公司编码", binding.getRoot());
            return;
        }

        if (TextUtils.isEmpty(moduleCode)) {
            ToastUtil.showTextShort("未获取到需要操作的主模块编码", binding.getRoot());
            return;
        }

        if (TextUtils.isEmpty(bizType)) {
            ToastUtil.showTextShort("未获取到需要操作的业务类型", binding.getRoot());
            return;
        }
        Class<?> clazz;
        switch (moduleCode) {
            case Global.SETTING:
                clazz = Setting.class;
                break;
            default:
                clazz = Main.class;
                break;
        }
        Intent intent = new Intent(Home.this, clazz);
        Bundle bundle = new Bundle();
        bundle.putString(Global.EXTRA_COMPANY_CODE_KEY, companyCode);
        bundle.putString(Global.EXTRA_MODULE_CODE_KEY, moduleCode);
        bundle.putString(Global.EXTRA_BIZ_TYPE_KEY, bizType);
        bundle.putString(Global.EXTRA_REF_TYPE_KEY, refType);
        bundle.putString(Global.EXTRA_CAPTION_KEY, caption);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 获取仓储系统数据，缓存
     */
    private void getStoreInfo() {
        DialogHelper dialogHelper = new DialogHelper(this);
        dialogHelper.showLoadingDialog("正在获取库存地点信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_INCREMENTALINFO + "?queryType=ZZ", bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                //缓存仓库信息到本地
                DatabaseHelper.editSp(bo.incrementalInfoList, data);
//                List<IncrementalEntity> incrementalEntities = gson.fromJson(data, new TypeToken<List<IncrementalEntity>>() {
//                }.getType());
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    /**
     * //对返回键进行监听
     *
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showChooseDialog() {
        View rootView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_menu, null);
        GridView menu = (GridView) rootView.findViewById(R.id.gd_menus);
        ArrayList<BottomMenuEntity> items = new ArrayList<>();
        BottomMenuEntity item = new BottomMenuEntity();
        item.setMenuName("退出");
        item.setMenuImageRes(R.mipmap.icon_data_submit);
        items.add(item);

        item = new BottomMenuEntity();
        item.setMenuName("检查更新");
        item.setMenuImageRes(R.mipmap.icon_update);
        items.add(item);


        BottomDialogMenuAdapter adapter = new BottomDialogMenuAdapter(this, items);
        menu.setAdapter(adapter);

        final Dialog dialog = new Dialog(this, R.style.MaterialDialogSheet);
        dialog.setContentView(rootView);
        dialog.setCancelable(true);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.show();

        menu.setOnItemClickListener((adapterView, view, position, id) -> {
            switch (position) {
                case 0:
                    Intent intent = new Intent(MyAppcliation.context.getApplicationContext(), Login.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("type", 1);
                    MyAppcliation.context.startActivity(intent);
                    finish();
                    break;
                case 1:
                    updateTask();
                    break;
                default:

            }
            dialog.dismiss();
        });
    }

    /**
     * app更新
     */
    protected void updateTask() {
        DialogHelper dialogHelper = new DialogHelper(this);
        dialogHelper.showLoadingDialog("正在检查更新");
        bo.maps = Urls.getDefaultConfigrationMap();
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_UPDATE, bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                if (result.getData() != null) {
                    String data = gson.toJson(result.getData());
                    UpdateInfo update = gson.fromJson(data, UpdateInfo.class);
                    //判断是否需要更新
                    update(update);
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    /**
     * 判断是否更新app
     *
     * @param update
     */
    public void update(UpdateInfo update) {
        if (Update.isNeedUpdate(update.getVersion(), this)) {
            loadNewVersionAlertDiaLog(update);
        } else {
            ToastUtil.showTextShort("已经是最新版本！");
        }
    }

    /**
     * 更新提示框
     *
     * @param update
     */
    public void loadNewVersionAlertDiaLog(UpdateInfo update) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("更新说明");
        alert.setMessage(update.getMsg());
        /**
         * 点击弹窗之外区域，弹框不消失
         */
        alert.setCancelable(false);
        alert.setPositiveButton("立即更新", (dialog, which) -> {
            try {
                download(this, update, "app.apk");
            } catch (Exception e) {
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("下载文件出错" + e.getMessage())
                        .setPositiveButton("确定", (dialog1, which1) -> {
                            if (update.getIsPower() == 0) {
                            } else {
                                finish();
                            }
                        })
                        .create()
                        .show();
            }

        });
        if (update.getIsPower() == 0) {
            alert.setNegativeButton("暂不更新", (dialog, which) -> {
                //如果不更新，则进入正常登录流程
            });
        }
        alert.create();
        alert.show();
    }

    /**
     * app下载
     *
     * @param mContext
     * @param update
     * @param fileName
     */
    public void download(Context mContext, UpdateInfo update, String fileName) {
        binding.progressbar.setVisibility(View.VISIBLE);
        DownloadUtil.download(mContext, update.getUrl(), fileName, new DownloadProgressListener() {
            @Override
            public void onDownloadProgress(long sumReaded, long content, boolean done) {
                binding.progressbar.setProgress((int) (sumReaded * 100 / content));
            }

            @Override
            public void onDownloadResult(String filePath, long sumReaded, long content, boolean done) {
                if (done) {
                    runOnUiThread(() -> {
                        binding.progressbar.setVisibility(View.GONE);
                        ToastUtil.showTextLong("下载完成，开始安装！");
                        DownloadUtil.installAPK(mContext, filePath, fileName);
                    });
                } else {
                    runOnUiThread(() -> {
                        binding.progressbar.setVisibility(View.GONE);
                        ToastUtil.showTextShort("下载不完整！");
                        //如果不更新，则进入正常登录流程
                    });
                }
            }

            @Override
            public void onFailResponse() {

                runOnUiThread(() -> {
                    binding.progressbar.setVisibility(View.GONE);
                    ToastUtil.showTextShort("下载失败！");
                    //如果不更新，则进入正常登录流程
                });
            }
        });

    }

}